package com.yangrong.thread.chapter10;

/**
 * 给程序添加hook钩子，当程序异常中断或被kill时可以捕获并释放资源，kill -9无法捕获，程序会直接中断
 * 
 * @author YangRong
 * @date 2020年5月29日
 */
public class ExitCapture {

	public static void main(String[] args) {
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			System.out.println("The application will be exit.");
			notifyAndRelease();
		}));

		int i = 0;
		while (true) {
			try {
				Thread.sleep(1_000);
				System.out.println("I am working...");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;
			if (i > 20) {
				throw new RuntimeException("Error");
			}
		}
	}

	private static void notifyAndRelease() {
		System.out.println("notify to the admin.");
		try {
			Thread.sleep(1_000);
		} catch (InterruptedException e) {
		}

		System.out.println("will release resource(socket,file,connection)");

		try {
			Thread.sleep(1_000);
		} catch (InterruptedException e) {
		}

		System.out.println("Release and notify done.");
	}

}
